package com.cy.pj.modules.service.impl;

import com.cy.pj.common.bo.PageObject;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.utils.ShiroUtils;
import com.cy.pj.modules.entity.AfStock;
import com.cy.pj.modules.entity.Shop;
import com.cy.pj.modules.entity.Sku;
import com.cy.pj.modules.mapper.AfStockMapper;
import com.cy.pj.modules.mapper.ShopMapper;
import com.cy.pj.modules.mapper.SkuMapper;
import com.cy.pj.modules.service.IAfStockService;
import com.cy.pj.modules.service.ISkuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author kiven
 * @date 2023-03-19
 */
@Service
public class AfStockServiceImpl implements IAfStockService {
    @Autowired
    private AfStockMapper afStockMapper;
    @Value("${fz.pageHelper.pageSize}")
    private Integer pageSize;

    @Value("${fz.inventoryWarning}")
    private Long inventoryWarning;

    @Autowired
    private ShopMapper shopMapper;

    // 用于扣减库存 执行修改
    @Autowired
    private ISkuService skuService;

    @Autowired
    private SkuMapper skuMapper;



    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public AfStock selectAfStockById(Long id) {
        return afStockMapper.selectAfStockById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param afStock 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public PageObject<AfStock> selectAfStockList(AfStock afStock, Integer pageCurrent) {
        //1.参数校验
        if (pageCurrent == null || pageCurrent < 1) {
            throw new IllegalArgumentException("页码值无效");
        }
        //2.设置分页参数
        String orderBy = "id desc";
        Page<AfStock> page = PageHelper.startPage(pageCurrent, pageSize, orderBy);
        //3.查询当前页记录
        List<AfStock> list = afStockMapper.selectAfStockList(afStock);
        return new PageObject<>(list, (int) page.getTotal(), page.getPages(), pageSize, pageCurrent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer sp(Long afStockId) {
        AfStock afStock = afStockMapper.selectAfStockByIdForUpdate(afStockId);
        if("1".equals(afStock.getStatu())){
            throw new ServiceException("已被审批");
        }

        //以下代码修改两边库存
        Sku sku1 = skuMapper.selectSkuById(Long.parseLong(afStock.getAfSku()));
        Shop shop = new Shop();
        shop.setName(afStock.getAfOldShop());
        Shop oldShop = shopMapper.selectShopList(shop).get(0);
        shop.setName(afStock.getAfShop());
        Shop targetShop = shopMapper.selectShopList(shop).get(0);
        // 判断其是不是该店铺 店长
        if (Long.parseLong(ShiroUtils.getUser().getId()+"")!=targetShop.getShopUserId()) {
            throw new ServiceException("请使用店长账号进行审批");
        }

        Sku sku = new Sku();
        sku.setSpecifications(sku1.getSpecifications());
        sku.setSpuId(sku1.getSpuId());
        sku.setShopId(oldShop.getId());
        Sku skus = skuMapper.selectSkuByShopIdAndSpecificationsAndSpu(sku);
        sku.setShopId(targetShop.getId());
        Sku targetSkus = skuMapper.selectSkuByShopIdAndSpecificationsAndSpu(sku);
        // 锁定当前这条数据 减少目标店铺的库存
        // 锁定当前这条数据 增加原店铺的库存,如果原店铺没有该sku 则新增,如果有sku,则增加数量
        Sku oldSkuForUpdate = skuMapper.selectSkuByIdForUpdate(skus.getId());
        Sku tarGetSkuForUpdate = skuMapper.selectSkuByIdForUpdate(targetSkus.getId());
        // 增加库存
        Sku oldSku = new Sku();
        oldSku.setId(oldSkuForUpdate.getId());
        oldSku.setNumber(oldSkuForUpdate.getNumber()+afStock.getAfNum());
        int i = skuService.updateSku(oldSku);
        // 减少库存
        Sku tarGetSku = new Sku();
        tarGetSku.setId(tarGetSkuForUpdate.getId());
        tarGetSku.setNumber(tarGetSkuForUpdate.getNumber()-afStock.getAfNum());
        int i1 = skuService.updateSku(tarGetSku);
        if (!(i==1&&i1==1)) {
            throw new ServiceException("操作失败,请稍后重试");
        }
        //补充afStock 批准人 和批准时间信息,当前状态改为1 然后修改该列
        afStock.setStatu("1");
        afStock.setRatifyUser(ShiroUtils.getUsername());
        afStock.setRetifyTime(new Date());
        return afStockMapper.updateAfStock(afStock);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param afStock 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertAfStock(AfStock afStock) {

        // 查看当前用户id 和店铺属实 只能申请本店铺的库存
        Shop shop = shopMapper.selectShopById(Long.parseLong(ShiroUtils.getUser().getShopId()));
        if (!(shop != null && (afStock.getAfOldShop().equals(shop.getName())))) {
            throw new ServiceException("只能申请本店铺的库存");
        }
        // 查看当前店铺 该sku数量是否很少或者没有该sku 根据spuid和shopid以及规格来申请
        Sku sku = skuMapper.selectSkuById(Long.parseLong(afStock.getAfSku()));
        // 标准 spuId shopId sku规格 来找货
        Sku sku1 = new Sku();
        sku1.setShopId(shop.getId());
        sku1.setSpecifications(sku.getSpecifications());
        sku1.setSpuId(sku.getSpuId());
        Sku skus = skuMapper.selectSkuByShopIdAndSpecificationsAndSpu(sku1);
        if (skus == null ) {
            throw new ServiceException("请联系店长添加该品");
        }
        if (skus.getNumber() >= inventoryWarning) {
            throw new ServiceException("请于库存低于" + inventoryWarning + "再申请");
        }
        // 查看目标店铺是否有库存
        Shop shopTarget = new Shop();
        shopTarget.setName(afStock.getAfShop());
        List<Shop> shops = shopMapper.selectShopList(shopTarget);
        if (shops == null || shops.size() != 1) {
            throw new ServiceException("该店铺不存在");
        }
        sku1.setShopId(shops.get(0).getId());
        Sku targetSkus = skuMapper.selectSkuByShopIdAndSpecificationsAndSpu(sku1);
        if (targetSkus == null ) {
            throw new ServiceException("目标店铺,该品不存在,请确认后重新输入");
        }
        if (targetSkus.getNumber() <= inventoryWarning) {
            throw new ServiceException("目标店铺库存低于" + inventoryWarning + ",请申请采购或向其他店铺申请");
        }
        // 完善数据,时间,审批等等
        afStock.setAddTime(new Date());
        afStock.setAfUser(ShiroUtils.getUsername());
        afStock.setShopId(shops.get(0).getId()+"");
        afStock.setStatu("0");
        return afStockMapper.insertAfStock(afStock);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param afStock 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateAfStock(AfStock afStock) {
        return afStockMapper.updateAfStock(afStock);
    }


    /**
     * 删除【请填写功能名称】对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAfStockByIds(String ids) {
        return afStockMapper.deleteAfStockByIds(ids.split(","));
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteAfStockById(Long id) {
        return afStockMapper.deleteAfStockById(id);
    }


}
